function numberTotal(num1,num2){
let total = num1 * num2;
console.log('total=' + total);
}
numberTotal(20,10);
console.log(total); //total is not defined
宣告區域變數在function內,只有在呼叫function時,才會被執行,當function執行完畢後,記憶體會被釋放,所以total會找不到
let a = 3;
let b = 4
let c = a + b;
function number(){
let a = 2;
let b = 3;
let c = a+b;
console.log('區域a =' + a); //2
console.log('區域b =' + b); //3
console.log('區域c =' + c); //5
}
number();
console.log('全域a =' + a); //3
console.log('全域b =' + b); //4
console.log('全域c =' + c); //7
新手常犯的錯誤會將變數都宣告全域變數,隨時隨地都可以使用,雖然方便,但是當有大量程式碼的時候,一不小心就會改到全域變數的值,導致執行結果不正確,不僅難除錯,又很耗記憶體。